package com.xue.my.protocol.codec;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.xue.my.json.fastjson.FastJsonUtils;
import com.xue.my.protocol.AbstractMessage;
import com.xue.my.protocol.MessageDecoder;
import com.xue.my.util.common.GzipUtils;
import com.xue.my.util.encrypt.SecurityCoder;

/**   
 * @Title: JsonMessageDecoder.java 
 * @Package com.xue.my.protocol.codec 
 * @Description: TODO
 * @author jimmy lovelyxuehanxin@163.com   
 * @date 2013-7-27 下午3:40:30 
 */
public class JsonMessageDecoder implements MessageDecoder{
	
	private SecurityCoder byteSecurityCoder;

	public AbstractMessage messageDecode(HttpServletRequest request, HttpServletResponse response) {
		
		String jsonString = null;
		
		String encry = request.getHeader("encry");
		String gzip = request.getHeader("gzip");
		
		try {
			byte[] data  = null;
			if("1".equals(encry)){
				data = IOUtils.toByteArray(request.getInputStream());
				data = byteSecurityCoder.decode(data);
			}
			
			if("1".equals(gzip)){
				data = GzipUtils.decompress(data);
			}
			jsonString = IOUtils.toString(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
		AbstractMessage abstractMessage = new AbstractMessage(request, response);
		abstractMessage.setHttpBody(jsonString);
		return abstractMessage;
	}

}
